package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.WorkSpaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author bairimengchang
 * @version 1.0
 * @project sky-take-out
 * @description
 * @date 2024/08/29 16:09:52
 */
@Service
@Slf4j
public class WorkSpaceServiceImpl implements WorkSpaceService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 查询今日运营数据
     * @return 今日运营数据返回的数据格式
     */
    @Override
    public BusinessDataVO getBusinessData() {
        BusinessDataVO businessDataVO = new BusinessDataVO();

        // 获得当天的开始时间
        LocalDateTime begin = LocalDateTime.now().with(LocalTime.MIN);
        // 获得当天的结束时间
        LocalDateTime end = LocalDateTime.now().with(LocalTime.MAX);

        // 构建一个简单的查询对象
        Map<String, Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);

        // 查询当天订单总数
        Integer totalOrder = ordersMapper.countByMap(map);
        log.info("查询当天订单总数：{}", totalOrder);

        // 加入有效订单条件
        map.put("status", Orders.COMPLETED);

        // 有效订单数（有效订单）
        Integer validOrderCount = ordersMapper.countByMap(map);
        businessDataVO.setValidOrderCount(validOrderCount);
        log.info("有效订单数：{}", validOrderCount);

        // 营业额（有效订单）
        Double turnover = ordersMapper.sumTurnoverByMap(map);
        turnover = turnover == null ? 0.0 : turnover;
        businessDataVO.setTurnover(turnover);
        log.info("营业额：{}", turnover);

        // 计算订单完成率（避免整数除法导致的结果精度丢失）
        // 订单完成率
        double orderCompletionRate;
        if (totalOrder == 0) {
            // 设置一个默认值或特殊值
            orderCompletionRate = 0.0;
        } else {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrder;
        }
        businessDataVO.setOrderCompletionRate(orderCompletionRate);
        log.info("订单完成率：{}", orderCompletionRate);

        // 平均客户单价（营业额/有效订单）
        Double unitPrice = turnover / validOrderCount;
        businessDataVO.setUnitPrice(unitPrice);
        log.info("平均客户单价：{}", unitPrice);

        // 新增用户数（账户创建时间是当天的）
        Integer newUsers = userMapper.countUsersByMap(map);
        businessDataVO.setNewUsers(newUsers);
        log.info("新增用户数：{}", newUsers);

        return businessDataVO;
    }

    /**
     * 查询菜品总览
     * @return 菜品总览返回的数据格式
     */
    @Override
    public DishOverViewVO getOverviewDishes() {
        // 构建一个简单的查询对象
        Map<String, Object> map = new HashMap<>();

        // 查询已启售菜品数量
        map.put("status", StatusConstant.ENABLE);
        Integer sold = dishMapper.countByMap(map);
        log.info("已启售菜品数量：{}", sold);

        // 查询已停售菜品数量
        map.put("status", StatusConstant.DISABLE);
        Integer discontinued = dishMapper.countByMap(map);
        log.info("已停售菜品数量：{}", discontinued);

        return DishOverViewVO.builder().sold(sold).discontinued(discontinued).build();
    }

    /**
     * 查询套餐总览
     * @return 套餐总览返回的数据格式
     */
    @Override
    public SetmealOverViewVO getOverviewSetmeals() {
        // 构建一个简单的查询对象
        Map<String, Object> map = new HashMap<>();

        // 查询已启售套餐数量
        map.put("status", StatusConstant.ENABLE);
        Integer sold = setmealMapper.countByMap(map);
        log.info("已启售套餐数量：{}", sold);

        // 查询已停售套餐数量
        map.put("status", StatusConstant.DISABLE);
        Integer discontinued = setmealMapper.countByMap(map);
        log.info("已停售套餐数量：{}", discontinued);

        return SetmealOverViewVO.builder().sold(sold).discontinued(discontinued).build();
    }

    /**
     * 查询订单总览
     * @return 订单管理数据返回的数据格式
     */
    @Override
    public OrderOverViewVO getOverviewOrders() {
        OrderOverViewVO orderOverViewVO = new OrderOverViewVO();
        // 构建一个简单的查询对象
        Map<String, Object> map = new HashMap<>();

        // 待接单数量
        map.put("status", Orders.TO_BE_CONFIRMED);      // 状态是待接单1
        Integer waitingOrders = ordersMapper.countByMap(map);
        log.info("待接单数量：{}", waitingOrders);
        orderOverViewVO.setWaitingOrders(waitingOrders);

        // 待派送数量
        map.put("status", Orders.CONFIRMED);        // 状态是已接单3
        Integer deliveredOrders = ordersMapper.countByMap(map);
        log.info("待派送数量：{}", deliveredOrders);
        orderOverViewVO.setDeliveredOrders(deliveredOrders);

        // 已完成数量
        map.put("status", Orders.COMPLETED);        // 状态是已完成5
        Integer completedOrders = ordersMapper.countByMap(map);
        log.info("已完成数量：{}", completedOrders);
        orderOverViewVO.setCompletedOrders(completedOrders);

        // 已取消数量
        map.put("status", Orders.CANCELLED);        // 状态是已取消6
        Integer cancelledOrders = ordersMapper.countByMap(map);
        log.info("已取消数量：{}", cancelledOrders);
        orderOverViewVO.setCancelledOrders(cancelledOrders);

        // 全部订单
        map.put("status", null);
        Integer allOrders = ordersMapper.countByMap(map);
        orderOverViewVO.setAllOrders(allOrders);
        log.info("全部订单：{}", allOrders);

        log.info("订单总览：{}", orderOverViewVO);
        return orderOverViewVO;
    }
}
